package org.southyin.securitysamples.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.southyin.securitysamples.mapper.MenuMapper;
import org.southyin.securitysamples.model.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class MenuService {
    @Autowired
    MenuMapper menuMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    public List<Menu> getMenuRoles() {
        try {
            String menuAndRole = redisTemplate.opsForValue().get("menuAndRole");
            List<Menu> menuRoles = null;
            if (menuAndRole == null) {
                menuRoles = menuMapper.getMenuRoles();
                redisTemplate.opsForValue().set("menuAndRole", new ObjectMapper().writeValueAsString(menuRoles));
                redisTemplate.expire("menuAndRole", 300, TimeUnit.SECONDS);
                return menuRoles;
            }
            else{
                List<Menu> list = null;
                list = new ObjectMapper().readValue(menuAndRole, new TypeReference<List<Menu>>(){});
                return list;
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
